// 路由访问后，直接能渲染
<template>
  <div class="login_container">
    <div class="login_box">
      <div class="title">
        博客-登录
      </div>
      <div class="login_form">
        <el-form
          ref="form"
          label-width="0px"
          :model="loginFormData"
          :rules="rules"
          @keyup.enter="subForm(form)"
        >
          <el-form-item prop="username">
            <el-input
              placeholder="请输入用户名"
              autofocus
              clearable
              v-model="loginFormData.username"
              maxlength="6"
            >
              <template #prepend>
                账号
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              placeholder="请输入密码"
              type="password"
              show-password
              v-model="loginFormData.password"
              maxlength="20"
            >
              <template #prepend>
                密码
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              placeholder="请输入验证码"
              v-model="loginFormData.captcha"
              maxlength="20"
            >
              <template #prepend>
                验证码
              </template>
              <template #suffix>
                <img
                  :src="captchaSrc"
                  style="width:100%;height:100%;"
                  @click="loadCaptcha"
                >
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="btns">
            <!-- button组件 -->
            <el-button
              type="primary"
              :loading="loading"
              @click="subForm(form)"
            >
              登录
            </el-button>
            <el-button
              type="info"
              @click="resetForm(form)"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  getCurrentInstance, // 获取当前对象，相当于this
  onMounted
} from 'vue'
import {
  FormInstance, // 获取表单对象
  FormRules,
  ElMessage
} from 'element-plus'

import LoginService from './service/LoginService'
import { store } from '@/store'
// 对象实例化
const loginService = new LoginService()

// 表单对象,类型为FormInstance
const form = ref<FormInstance>()

// loading加载动画，默认不显示
const loading = ref(false)

const {
  proxy
} = getCurrentInstance() as any

// 双向绑定属性：
const loginFormData = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 动态属性：验证码
const captchaSrc = ref('')
onMounted(() => {
  loadCaptcha()
  console.log(form.value)
})
// 加载/更新验证码
const loadCaptcha = async () => {
  const captcha = await loginService.captcha()
  captchaSrc.value = captcha
}

// 设置规则
const rules = reactive < FormRules >({
  username: [{
    required: true,
    message: '请输入帐号',
    trigger: 'blur'
  }, {
    min: 2,
    max: 6,
    message: '帐号长度需要在2-6之间',
    trigger: 'blur'
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  }, {
    min: 6,
    max: 20,
    message: '密码长度需要在6-20之间',
    trigger: 'blur'
  }],
  captcha: [{
    required: true,
    message: '请输入验证码',
    trigger: 'blur'
  }]
})

// 提交表单
const subForm = async (form:FormInstance|undefined) => {
  // 1、验证表单数据
  if (!form) return
  await form.validate(async (valid, fields) => {
    if (!valid) return
    // 2、验证通过，加载动画
    loading.value = true
    const { code, data } = await loginService.login(loginFormData)
    if (code === 0) {
      ElMessage.success('登录成功')
      // 保存用户数据
      store.commit('setUser', data?.userInfo)
      store.commit('setToken', data?.token)
      // 登录成功跳转页面
      proxy.$router.push('/home/home')
    } else {
      // 清空搜索框
      form.resetFields()
    }
    loading.value = false
  })
}

// 清空表单
const resetForm = (form:FormInstance|undefined) => {
  if (!form) return
  form.resetFields()
}
</script>

<style lang="scss" scoped>
    .login_container {
        height: 100vh;
        background-color: #2b4b6b;
        position: relative;
    }

    .login_box {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 500px;
        height: 400px;
        border-radius: 3px;
        background-color: rgba(255, 255, 255, 0.8);
    }

    .title {
        position: absolute;
        top: 40px;
        width: 100%;
        height: 50px;
        text-align: center;
        line-height: 50px;
        font-size: 18px;
    }

    .login_form {
        position: absolute;
        top: 120px;
        width: 80%;
        left: 10%;
        height: 280px;
        padding: 0 20px;
        box-sizing: border-box;
    }
    .el-input{
      height: 40px!important;
      margin-bottom: 8px !important;
    }

    .btns {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px !important;
    }
</style>
